import {Injectable} from '@angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, CanDeactivate} from '@angular/router';
import {Observable} from 'rxjs';
import {NzModalService} from 'ng-zorro-antd/modal';

@Injectable()
export class LeavePageGuard implements CanDeactivate<any> {
  constructor(private nzModalService: NzModalService) {
  }

  async canDeactivate(component: any,
                      currentRoute: ActivatedRouteSnapshot,
                      currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot) {
    let confirm: any = false;
    if (currentRoute.queryParams.operationType === 'view' || component['isSaved']) {
      return true;
    }
    confirm = await this.confirm();
    return confirm;
  }

  confirm() {
    return new Promise((resolve, reject) => {
      this.nzModalService.confirm({
        nzTitle: '警告',
        nzContent: '<b>离开页面将不会保存数据，确定要离开吗?</b>',
        nzOkText: '确定',
        nzOkType: 'primary',
        nzOkDanger: true,
        nzOnOk: () => {
          resolve(true);
        },
        nzCancelText: '取消',
        nzOnCancel: () => {
          resolve(false);
        }
      });
    });
  }

}
